/** 
 * Project Name: farm-core 
 * File Name: BuguException.java 
 * Package Name: com.bugull.farm.core.frame.exception 
 * Date: 2017年3月23日上午11:08:30 
 * Copyright (c) 2017, hadlinks All Rights Reserved. 
 * 
 */
package com.bugull.farm.core.frame.exception;

import java.util.Arrays;
import java.util.List;

import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.cache.ProtocolCache;
import com.bugull.farm.core.frame.structure.Param;
import com.bugull.farm.core.utils.ByteUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/** 
 * ClassName: BuguException 
 * Function: TODO ADD FUNCTION.  
 * date: 2017年3月23日 上午11:08:30  
 * 
 * @author songwei (songw@hadlinks.com)
 * @version 
 * @since JDK 1.8 
 */
public class BuguException extends Exception{

	private final byte errorCode;
	
	private byte[] msg;

	/**
	 * 构造函数
	 * @param errorCode
	 * @param in
	 * @param message
	 */
	public BuguException(byte errorCode, byte[] msg, String message){
		super(message);
		this.errorCode = errorCode;
		this.msg = msg;
	}
	
	/**
	 * 拼装服务器反馈的错误信息
	 * @param errorCode
	 * @param msg
	 * @return
	 */
	public ByteBuf getErrorResponse(){
		ByteBuf buf = Unpooled.buffer();
		//设置PV
		buf.writeZero(PropertiesCache.getInstance().getInt("frame.min.size"));
		List<Param> headList = ProtocolCache.getInstance().getHead();
		headList.forEach((param) -> {
			if(PropertiesCache.getInstance().getProps().containsKey(param.getName())){
				buf.setBytes(ProtocolCache.getInstance().getIndex(param.getName()), PropertiesCache.getInstance().getBytes(param.getName()));
			}else{
				buf.setBytes(ProtocolCache.getInstance().getIndex(param.getName()), Arrays.copyOfRange(msg, ProtocolCache.getInstance().getIndex(param.getName()), param.getLen()));
			}
		});
		//设置cmd
		buf.setByte(ProtocolCache.getInstance().getIndex("cmd"), PropertiesCache.getInstance().getByte("cmd.error"));
		//设置errorCmd
		buf.writeByte(msg[ProtocolCache.getInstance().getIndex("cmd")]);
		//设置errorCode
		buf.writeByte(errorCode);
		//重新计算长度
		int len = buf.readableBytes() - 1 - ProtocolCache.getInstance().getIndex("len");
		buf.setByte(ProtocolCache.getInstance().getIndex("len"), ByteUtil.fromInt(len)[2]);
		buf.setByte(ProtocolCache.getInstance().getIndex("len"), ByteUtil.fromInt(len)[3]);
		//重新设置协议序号
		buf.setBytes(ProtocolCache.getInstance().getIndex("serial"), PropertiesCache.getInstance().getBytes("serial"));
		return buf;
	}
}
